import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'plant_challenge_page_controller.dart';
import '../../../function/model/post_model.dart';
import '../../../function/state/like_state.dart';
import '../../../function/utils/my_common.dart';

/// 植物种植活动挑战页面
class PlantChallengePage extends GetView<PlantChallengePageController> {
  const PlantChallengePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部轮播图区域
              _buildTopCarouselSection(context),

              // 瀑布流帖子列表
              Expanded(child: _buildPostsListSection(context)),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部轮播图区域
  Widget _buildTopCarouselSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Activity Challenge 标题
        Padding(
          padding: EdgeInsets.only(left: 16.w, top: 0.h, bottom: 20.h),
          child: Row(
            children: [
              Icon(
                Icons.arrow_back_ios_new,
                size: 20.sp,
                color: MyCommonUtils.white,
              ).padding(all: 10.w).inkWell(onTap: () => Get.back()),

              Expanded(
                child:
                    Text(
                      'Planting Challenge',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: MyCommonUtils.white,
                        fontFamily:
                            GoogleFonts.berkshireSwash(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                      ),
                    ).center(),
              ),

              SizedBox(width: 36.w),
            ],
          ),
        ),

        // 轮播图
        SizedBox(
          width: double.infinity,
          height: 152.h, // 根据宽高比 358/152 计算
          child: CarouselSlider(
            options: CarouselOptions(
              viewportFraction: 0.75, // 显示75%的宽度，让左右两边可见
              enlargeCenterPage: true, // 放大中心页面
              autoPlay: true, // 自动播放
              autoPlayInterval: Duration(seconds: 5), // 自动播放间隔
              autoPlayAnimationDuration: Duration(milliseconds: 800),
              autoPlayCurve: Curves.fastOutSlowIn,
              pauseAutoPlayOnTouch: true,
              pauseAutoPlayOnManualNavigate: true,
              enableInfiniteScroll: true,
              reverse: false,
              onPageChanged: (index, reason) {
                controller.onCarouselPageChanged(index);
              },
            ),
            items:
                controller.categories.asMap().entries.map((entry) {
                  final index = entry.key;
                  final category = entry.value;
                  return _buildCarouselItem(context, index, category);
                }).toList(),
          ),
        ),

        SizedBox(height: 10.h),

        // 轮播图指示器
        _buildCarouselIndicators(),

        SizedBox(height: 20.h),
      ],
    );
  }

  /// 构建轮播图指示器
  Widget _buildCarouselIndicators() {
    return GetX<PlantChallengePageController>(
      builder: (controller) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: List.generate(controller.categories.length, (index) {
            final isSelected = controller.carouselIndex == index;
            return AnimatedContainer(
              duration: Duration(milliseconds: 300),
              margin: EdgeInsets.symmetric(horizontal: 4.w),
              width: isSelected ? 24.w : 14.w,
              height: 4.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.r),
                color:
                    isSelected
                        ? MyCommonUtils.orange
                        : MyCommonUtils.white.withValues(alpha: 0.3),
              ),
            );
          }),
        );
      },
    );
  }

  /// 构建轮播图单个项目
  Widget _buildCarouselItem(
    BuildContext context,
    int index,
    PostCategory category,
  ) {
    return AspectRatio(
      aspectRatio: 358 / 152,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(category.imagePath),
            fit: BoxFit.fill,
          ),
        ),
      ),
    );
  }

  /// 构建帖子列表区域
  Widget _buildPostsListSection(BuildContext context) {
    return GetX<PlantChallengePageController>(
      builder: (controller) {
        final posts = controller.currentCategoryPosts;
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: AnimatedSwitcher(
            duration: Duration(milliseconds: 500),
            transitionBuilder: (Widget child, Animation<double> animation) {
              return FadeTransition(
                opacity: animation,
                child: SlideTransition(
                  position: Tween<Offset>(
                    begin: Offset(0.0, 0.3),
                    end: Offset.zero,
                  ).animate(
                    CurvedAnimation(
                      parent: animation,
                      curve: Curves.easeOutCubic,
                    ),
                  ),
                  child: child,
                ),
              );
            },
            child: MasonryGridView.count(
              key: ValueKey(controller.currentCategory),
              crossAxisCount: 2,
              mainAxisSpacing: 12.h,
              crossAxisSpacing: 12.w,
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final post = posts[index];
                return _buildPostCard(post, controller);
              },
            ),
          ),
        );
      },
    );
  }

  /// 构建帖子卡片
  Widget _buildPostCard(
    PostModel post,
    PlantChallengePageController controller,
  ) {
    // 为瀑布流创建不同的高度
    final randomHeight = (post.id.hashCode % 3) + 1; // 1, 2, 3
    final imageHeight = (160 + randomHeight * 20).h; // 160, 180, 200

    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 300),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        return Transform.scale(
          scale: 0.8 + (0.2 * value),
          child: Opacity(
            opacity: value,
            child: GestureDetector(
              onTap: () {
                // 导航到帖子详情页
                Get.toNamed('/post-detail', arguments: post);
              },
              child: Container(
                decoration: BoxDecoration(
                  color: MyCommonUtils.white,
                  borderRadius: BorderRadius.circular(12.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1 * value),
                      blurRadius: 8.r,
                      offset: Offset(0, 2.h),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 帖子图片 - 瀑布流不同高度
                    Container(
                      height: imageHeight,
                      width: double.infinity,
                      child: _buildPostImage(post),
                    ),

                    // 帖子标题
                    Padding(
                      padding: EdgeInsets.all(8.w),
                      child: Text(
                        post.title,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w700,
                          color: MyCommonUtils.black,
                          height: 1.2,
                        ),
                        maxLines: randomHeight == 1 ? 1 : 2, // 根据高度调整行数
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),

                    // 用户信息和点赞
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 8.w),
                      child: Row(
                        children: [
                          // 用户头像和用户名
                          Expanded(
                            child: Row(
                              children: [
                                CircleAvatar(
                                  radius: 12.w, // 24.w / 2
                                  backgroundImage: AssetImage(
                                    controller.getUserAvatar(post.userId),
                                  ),
                                ),
                                SizedBox(width: 4.w),
                                Expanded(
                                  child: Text(
                                    controller.getUserName(post.userId),
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: MyCommonUtils.grey,
                                      fontWeight: FontWeight.w700,
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ],
                            ),
                          ),

                          // 点赞按钮和数量
                          GetX<LikeState>(
                            builder: (likeState) {
                              final isLiked = controller.isPostLiked(post.id);
                              final likes = controller.getPostLikes(post.id);
                              return Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    isLiked
                                        ? Icons.favorite
                                        : Icons.favorite_border,
                                    size: 22.w,
                                    color:
                                        isLiked
                                            ? MyCommonUtils.pink
                                            : MyCommonUtils.grey,
                                  ).onTap(
                                    () => controller.togglePostLike(post.id),
                                  ),
                                  SizedBox(width: 2.w),
                                  Text(
                                    likes.toString(),
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      color: MyCommonUtils.grey,
                                    ),
                                  ),
                                ],
                              );
                            },
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 8.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建帖子图片
  Widget _buildPostImage(PostModel post) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.r),
          topRight: Radius.circular(12.r),
        ),
        image: DecorationImage(
          image: AssetImage(
            post.resourceType == ResourceType.video
                ? (post.coverImagePath ?? post.resourcePath)
                : post.resourcePath,
          ),
          fit: BoxFit.cover,
        ),
      ),
      child:
          post.resourceType == ResourceType.video
              ? Center(
                child: Container(
                  width: 32.w,
                  height: 32.w,
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.6),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.play_arrow,
                    color: MyCommonUtils.white,
                    size: 20.sp,
                  ),
                ),
              )
              : null,
    );
  }
}
